from django.utils.decorators import method_decorator

from gis.admin.decorators import require_login, check_permission
from gis.common import track_logging
from gis.common.django_ext.decorators import validate_parameters
from gis.common.django_ext.views import BaseView
from itpay.core.agency import agency_service
from itpay.core.conf import IMConf
from itpay.core.mch import service
from itpay.server_admin.view.agency import helper
from itpay.server_admin.view.im.forms import (
    ListTopicSchema,
    TopicMessagesSchema,
    MessagesSchema,
)
from itpay.utils import rpc

_LOGGER = track_logging.getLogger(__name__)


class ListTopicView(BaseView):
    @method_decorator(require_login)
    @method_decorator(check_permission("agency_chat_get"))
    @method_decorator(validate_parameters(ListTopicSchema))
    def get(self, request, cleaned_data):
        cleaned_data["app_id"] = IMConf.app_id

        parent_name = cleaned_data.get("parent_name")
        if parent_name is not None:
            del cleaned_data["parent_name"]

        agency_name = cleaned_data.get("agency_name")
        if agency_name is not None:
            del cleaned_data["agency_name"]

        agency_id = cleaned_data.get("agency_id")
        if agency_id is not None:
            del cleaned_data["agency_id"]

        parent_id = cleaned_data.get("parent_id")
        if parent_id is not None:
            del cleaned_data["parent_id"]

        if agency_name or parent_name or agency_id or parent_id:
            _, agencies = agency_service.list_agency(
                1,
                100,
                id=agency_id,
                agency_name=agency_name,
                parent_name=parent_name,
                parent_id=parent_id,
            )

            if not agencies:
                return {"total": 0, "list": []}
            agency_ids = ",".join([str(e["id"]) for e in agencies])
            cleaned_data["agency_ids"] = agency_ids

        cleaned_data["is_replied"] = (
            -1
            if cleaned_data.get("is_replied") is None
            else 1
            if cleaned_data["is_replied"]
            else 0
        )

        response = rpc.do_get(
            IMConf.host + "open/pay/messages/topics/", cleaned_data, IMConf.api_key
        )
        if response.get("data") and response.get("data").get("list"):
            lll = []
            for e in response["data"]["list"]:
                try:
                    mch = service.get_mch(e["player_mch_id"])
                    e["player_mch"] = dict(id=mch["id"], name=mch["name"])
                    del e["player_mch_id"]
                    lll.append(helper.wrapper_agency_name(e))
                except Exception:
                    _LOGGER.info("wrap agency fail", exc_info=True)
            response["data"]["list"] = lll
        else:
            return {"total": 0, "list": []}
        return response["data"]


class ListTopicMessagesView(BaseView):
    @method_decorator(require_login)
    @method_decorator(check_permission("agency_chat_detail_get"))
    @method_decorator(validate_parameters(TopicMessagesSchema))
    def get(self, request, topic_id, cleaned_data):
        cleaned_data["app_id"] = IMConf.app_id
        response = rpc.do_get(
            IMConf.host + "open/pay/messages/topics/{}/".format(topic_id),
            cleaned_data,
            IMConf.api_key,
        )
        if "agency" not in response["data"]:
            raise Exception("Error IM Server")

        del response["data"]["agency"]["platform"]

        mch = service.get_mch(response["data"]["player"]["platform"]["id"])
        response["data"]["player"]["mch"] = dict(id=mch["id"], name=mch["name"])
        del response["data"]["player"]["platform"]

        return response["data"]


class ListMessagesView(BaseView):
    @method_decorator(require_login)
    @method_decorator(check_permission("agency_chat_detail_get"))
    @method_decorator(validate_parameters(MessagesSchema))
    def get(self, request, cleaned_data):
        cleaned_data["app_id"] = IMConf.app_id
        response = rpc.do_get(
            IMConf.host + "open/pay/messages/", cleaned_data, IMConf.api_key
        )
        if "agency" not in response["data"]:
            raise Exception("Error IM Server")

        del response["data"]["agency"]["platform"]

        mch = service.get_mch(response["data"]["player"]["platform"]["id"])
        response["data"]["player"]["mch"] = dict(id=mch["id"], name=mch["name"])
        del response["data"]["player"]["platform"]

        return response["data"]
